package com.funtonow.jqdk.ui;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.funtonow.jqdk.R;
import com.funtonow.jqdk.adapter.ApplyRecordAdapter;
import com.funtonow.jqdk.adapter.LoanListAdapter;
import com.funtonow.jqdk.base.BaseActivity;
import com.funtonow.jqdk.base.BaseBean;
import com.funtonow.jqdk.base.Constants;
import com.funtonow.jqdk.base.SqjAppliaction;
import com.funtonow.jqdk.base.UrlUtils;
import com.funtonow.jqdk.bean.ApplyRecordBean;
import com.funtonow.jqdk.bean.GameThirdInfoListBean;
import com.funtonow.jqdk.bean.LoanInfoBean;
import com.funtonow.jqdk.bean.UserInfoBean;
import com.funtonow.jqdk.utils.HttpUtil;
import com.funtonow.jqdk.utils.LogUtil;
import com.funtonow.jqdk.utils.SPUtil;
import com.funtonow.jqdk.utils.StatisticsUtils;
import com.funtonow.jqdk.utils.TimeUtils;
import com.funtonow.jqdk.utils.ToastUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.Call;

import static com.funtonow.jqdk.base.Constants.OWN_APP_ID;
import static com.funtonow.jqdk.base.UrlUtils.MY_APPLY_LIST;
import static com.funtonow.jqdk.base.UrlUtils.TUI_JIAN;
import static com.funtonow.jqdk.base.UrlUtils.UPDATE_MY_DK_INFO;

/**
 * @author Jiajien
 * @date 2019/6/26
 */
public class ApplyRecordActivity extends BaseActivity implements OnTimeSelectListener {

    @BindView(R.id.rlv_apply)
    RecyclerView rlvApply;
    @BindView(R.id.rlv_recommend)
    RecyclerView rlvRecommend;
    @BindView(R.id.ll_apply_record)
    LinearLayout llApplyRecord;
    @BindView(R.id.ll_recommend)
    LinearLayout llRecommend;

    private ApplyRecordAdapter applyRecordAdapter;
    private ApplyRecordBean applyRecordBean;

    private LoanListAdapter recommendAdapter;
    private List<GameThirdInfoListBean> gameThirdInfoListBeans = new ArrayList<>();

    private ApplyRecordBean.DataBean dataBean;

    @Override
    public int getLayoutRes() {
        return R.layout.activity_apply_record;
    }

    @Override
    public void onCreateActivity(@Nullable Bundle savedInstanceState) {
        initToolbar(getResources().getString(R.string.apply_record));
        initRecyclerView(rlvApply);
        initRecyclerView(rlvRecommend);
        recommendAdapter = new LoanListAdapter();
        rlvRecommend.setAdapter(recommendAdapter);
        applyRecordAdapter = new ApplyRecordAdapter();
        rlvApply.setAdapter(applyRecordAdapter);
        myApplyDk();
        getAppId();
        recommendAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (SPUtil.getUserInfo() != null && recommendAdapter.getItem(position).getVipfw() == 1
                        && SPUtil.getUserInfo().getHasVip() == 0) {
                    ToastUtils.show("该产品仅限会员申请");
                } else {
                    GameThirdInfoListBean gameThirdInfoListBean = recommendAdapter.getItem(position);
                    assert gameThirdInfoListBean != null;
                    StatisticsUtils.clickUrl(gameThirdInfoListBean);
                    StatisticsUtils.intentWebView(ApplyRecordActivity.this,
                            gameThirdInfoListBean.getUrl(),gameThirdInfoListBean.getName(),
                            gameThirdInfoListBean.getChanpinid());
                }
                finish();
            }
        });

        applyRecordAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                dataBean = applyRecordAdapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.tv_apply_agree:
                        updateDkInfo(position, dataBean.getSq().getLinkappid(), "已下款", "");
                        break;
                    case R.id.tv_apply_refuse:
                        updateDkInfo(position, dataBean.getSq().getLinkappid(), "被拒绝", "");
                        break;
                    case R.id.tv_apply_abandon:
                        updateDkInfo(position, dataBean.getSq().getLinkappid(), "个人放弃", "");
                        break;
                    case R.id.tv_update_payment_time:
                        TimePickerView pvTime = new TimePickerBuilder(ApplyRecordActivity.this, new OnTimeSelectListener() {
                            @Override
                            public void onTimeSelect(Date date, View v) {
                                updateDkInfo(position, dataBean.getSq().getLinkappid(), dataBean.getSq().getState(),
                                        TimeUtils.dateToString(date));
                            }
                        }).build();
                        pvTime.show();

                        break;
                    default:
                        break;
                }
            }
        });

    }

    private void initRecyclerView(RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        //设置增加或删除条目的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    /**
     * 推荐列表
     */
    private void recommend() {
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        param.put("showappid", Constants.DATA_APP_ID);
        HttpUtil.getInstance().postDataAsynToNet(TUI_JIAN, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                JSONObject jsonObject = JSON.parseObject(SqjAppliaction.loanInfoBean.getCpMap());
                String jsonArray = JSON.parseObject(jsonString).getJSONArray("data").toJSONString();
                List<String> stringList = JSON.parseArray(jsonArray, String.class);
                for (String s : stringList) {
                    for (LoanInfoBean.HeziInfoListBean heziInfoListBean : SqjAppliaction.loanInfoBean.getHeziInfoList()) {
                        if (s.equals(heziInfoListBean.getGdid())) {
                            for (LoanInfoBean.GdlistBean gdlistBean : SqjAppliaction.loanInfoBean.getGdlist()) {
                                if (s.equals(gdlistBean.getGdid())) {
                                    GameThirdInfoListBean gameThirdInfoListBean = JSON.parseObject(jsonObject.getJSONObject(gdlistBean.getChanpinid()).toJSONString(), GameThirdInfoListBean.class);
                                    gameThirdInfoListBean.setVipfw(gdlistBean.getVipfw());
                                    gameThirdInfoListBean.setUrl(gdlistBean.getUrl());
                                    gameThirdInfoListBean.setHeziId(heziInfoListBean.getType());
                                    gameThirdInfoListBean.setIndex(heziInfoListBean.getInde());
                                    gameThirdInfoListBean.setGdId(s);
                                    gameThirdInfoListBeans.add(gameThirdInfoListBean);
                                }
                            }
                        }
                    }
                }
                if (gameThirdInfoListBeans.size() > 0) {
                    if (gameThirdInfoListBeans.size() > 3) {
                        recommendAdapter.setNewData(gameThirdInfoListBeans.subList(0, 3));
                    } else {
                        recommendAdapter.setNewData(gameThirdInfoListBeans);
                    }
                    llRecommend.setVisibility(View.VISIBLE);
                } else {
                    llRecommend.setVisibility(View.GONE);
                }
                StatisticsUtils.baoGuang(Constants.HEZI_ID_25);
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    /**
     * 申请列表
     */
    private void myApplyDk() {
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        HttpUtil.getInstance().postDataAsynToNet(MY_APPLY_LIST, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                applyRecordBean = JSON.parseObject(jsonString, ApplyRecordBean.class);
                if (applyRecordBean.getErrnum() >= 0) {
                    if (applyRecordBean.getData().size() > 0) {
                        llApplyRecord.setVisibility(View.VISIBLE);
                        applyRecordAdapter.setNewData(applyRecordBean.getData());
                    } else {
                        llApplyRecord.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void failed(Call call, IOException e) {
                LogUtil.d("myApplyDk *******************  ");

            }
        });
    }

    /**
     * 修改申请信息
     */
    public void updateDkInfo(final int position, String id, final String state, final String payTime) {
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        param.put("dkappid", id);
        param.put("state", state);
        param.put("huan", payTime);
        HttpUtil.getInstance().postDataAsynToNet(UPDATE_MY_DK_INFO, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                BaseBean baseBean = JSON.parseObject(jsonString, BaseBean.class);
                if (baseBean.errnum >= 0) {
                    ApplyRecordBean.DataBean.SqBean sqBean = dataBean.getSq();
                    sqBean.setState(state);
                    sqBean.setHuan(payTime);
                    dataBean.setSq(sqBean);
                    applyRecordAdapter.setData(position, dataBean);

                }
            }

            @Override
            public void failed(Call call, IOException e) {
            }
        });
    }

    @Override
    public void onTimeSelect(Date date, View v) {

    }

    /**
     * 获取数据appId
     */
    private void getAppId() {
        HttpUtil.getInstance().getDataAsynFromNet(UrlUtils.GET_APPID, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                Constants.DATA_APP_ID = JSON.parseObject(jsonString).getString("appId");
                recommend();
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }


}
